package com.example.testplatform.controller;

import com.example.testplatform.common.LogUtils;
import com.example.testplatform.common.Result;
import com.example.testplatform.entity.TestApplication;
import com.example.testplatform.service.TestApplicationService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/applications")
public class TestApplicationController {
    
    private static final Logger logger = LogUtils.getLogger(TestApplicationController.class);
    
    @Autowired
    private TestApplicationService testApplicationService;
    
    // 获取测试申请单列表
    @GetMapping
    public Result<Map<String, Object>> getApplicationList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long applicantId,
            @RequestParam(required = false) Long testerId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        long startTimeTotal = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_LIST_QUERY_ATTEMPT", "system", "尝试获取测试申请单列表");
        LogUtils.logApiRequest(logger, "GET", "/api/applications", "page=" + page + ", pageSize=" + pageSize + ", productId=" + productId + ", status=" + status + ", applicantId=" + applicantId + ", testerId=" + testerId + ", startTime=" + startTime + ", endTime=" + endTime);
        
        // 保存原始参数的final版本用于日志记录
        final Integer originalPage = page;
        final Integer originalPageSize = pageSize;
        
        LogUtils.debug(logger, () -> "开始处理获取测试申请单列表请求，页码=" + originalPage + ", 每页数量=" + originalPageSize);
        
        try {
            // 验证参数
            if (page == null || page <= 0) {
                LogUtils.warn(logger, "分页查询参数无效: 页码必须大于0，当前页码=" + page);
                LogUtils.logBusiness(logger, "APPLICATION_LIST_QUERY_FAILED", "system", "分页查询参数无效: 页码必须大于0");
                page = 1;
                LogUtils.debug(logger, () -> "自动修正页码为默认值1");
            }
            
            if (pageSize == null || pageSize <= 0 || pageSize > 1000) {
                LogUtils.warn(logger, "分页查询参数无效: 每页数量必须在1-1000之间，当前值=" + pageSize);
                LogUtils.logBusiness(logger, "APPLICATION_LIST_QUERY_FAILED", "system", "分页查询参数无效: 每页数量必须在1-1000之间");
                pageSize = 10;
                LogUtils.debug(logger, () -> "自动修正每页数量为默认值10");
            }
            
            // 创建处理后参数的final版本
            final Integer finalPage = page;
            final Integer finalPageSize = pageSize;
            
            LogUtils.debug(logger, () -> "构建查询参数映射");
            Map<String, Object> params = new java.util.HashMap<>();
            params.put("productId", productId);
            params.put("status", status);
            params.put("applicantId", applicantId);
            params.put("testerId", testerId);
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            
            LogUtils.info(logger, () -> "执行获取测试申请单列表操作，页码=" + finalPage + ", 每页数量=" + finalPageSize);
            Map<String, Object> data = testApplicationService.getApplicationList(page, pageSize, params);
            
            LogUtils.debug(logger, () -> "获取测试申请单列表成功，返回结果包含total和list字段");
            LogUtils.logBusiness(logger, "APPLICATION_LIST_QUERY_SUCCESS", "system", "获取测试申请单列表成功，页码=" + finalPage + ", 每页数量=" + finalPageSize);
            LogUtils.logPerformance(logger, "getApplicationList", startTimeTotal, System.currentTimeMillis());
            
            LogUtils.info(logger, () -> "获取测试申请单列表请求处理完成，耗时=" + (System.currentTimeMillis() - startTimeTotal) + "ms");
            return Result.success(data);
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/applications", e);
            LogUtils.error(logger, "获取申请单列表过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_LIST_QUERY_FAILED", "system", "获取申请单列表失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "getApplicationList", startTimeTotal, System.currentTimeMillis());
            return Result.fail("获取申请单列表失败: " + e.getMessage());
        }
    }
    
    // 获取测试申请单详情
    @GetMapping("/{id}")
    public Result<TestApplication> getApplicationById(@PathVariable Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_DETAIL_QUERY_ATTEMPT", "system", "尝试获取测试申请单详情");
        LogUtils.logApiRequest(logger, "GET", "/api/applications/" + id, null);
        LogUtils.debug(logger, () -> "开始处理获取测试申请单详情请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "根据ID获取申请单详情参数无效: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_DETAIL_QUERY_FAILED", "system", "根据ID获取申请单详情参数无效: 申请单ID必须大于0");
                return Result.fail("申请单ID无效");
            }
            
            LogUtils.info(logger, () -> "执行根据ID获取测试申请单详情操作，申请单ID=" + id);
            TestApplication application = testApplicationService.getApplicationById(id);
            
            if (application != null) {
                LogUtils.debug(logger, () -> "获取测试申请单详情成功，申请单ID=" + id + ", 版本号=" + application.getVersion());
                LogUtils.logBusiness(logger, "APPLICATION_DETAIL_QUERY_SUCCESS", "system", "获取测试申请单详情成功，申请单ID=" + id + ", 版本号=" + application.getVersion());
                LogUtils.logPerformance(logger, "getApplicationById", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "获取测试申请单详情请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success(application);
            } else {
                LogUtils.warn(logger, "获取测试申请单详情失败: ID为" + id + "的申请单不存在");
                LogUtils.logBusiness(logger, "APPLICATION_DETAIL_QUERY_FAILED", "system", "申请单不存在，ID=" + id);
                return Result.fail("申请单不存在");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "GET", "/api/applications/" + id, e);
            LogUtils.error(logger, "获取申请单详情过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_DETAIL_QUERY_FAILED", "system", "获取申请单详情失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "getApplicationById", startTime, System.currentTimeMillis());
            return Result.fail("获取申请单详情失败: " + e.getMessage());
        }
    }
    
    // 创建测试申请单
    @PostMapping
    public Result<String> createApplication(@RequestBody TestApplication application) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_CREATE_ATTEMPT", "system", "尝试创建测试申请单");
        LogUtils.logApiRequest(logger, "POST", "/api/applications", application != null ? application.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理创建测试申请单请求");
        
        try {
            // 验证请求对象
            if (application == null) {
                LogUtils.warn(logger, "创建测试申请单失败: 申请单信息对象为空");
                LogUtils.logBusiness(logger, "APPLICATION_CREATE_FAILED", "system", "创建测试申请单失败: 申请单信息对象为空");
                return Result.fail("申请单信息无效");
            }
            
            LogUtils.debug(logger, () -> "获取创建测试申请单请求参数: 版本号=" + application.getVersion() + ", 产品ID=" + application.getProductId() + ", 申请人ID=" + application.getApplicantId());
            
            LogUtils.info(logger, () -> "执行创建测试申请单操作");
            boolean success = testApplicationService.createApplication(application);
            
            if (success) {
                LogUtils.debug(logger, () -> "创建测试申请单成功，申请单ID=" + application.getId() + ", 版本号=" + application.getVersion());
                LogUtils.logBusiness(logger, "APPLICATION_CREATE_SUCCESS", "system", "创建测试申请单成功，申请单ID=" + application.getId() + ", 版本号=" + application.getVersion());
                LogUtils.logPerformance(logger, "createApplication", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "创建测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("创建申请单成功");
            } else {
                LogUtils.warn(logger, "创建测试申请单失败: 未知原因");
                LogUtils.logBusiness(logger, "APPLICATION_CREATE_FAILED", "system", "创建测试申请单失败: 未知原因");
                return Result.fail("创建申请单失败");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "POST", "/api/applications", e);
            LogUtils.error(logger, "创建申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_CREATE_FAILED", "system", "创建申请单失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "createApplication", startTime, System.currentTimeMillis());
            return Result.fail("创建申请单失败: " + e.getMessage());
        }
    }
    
    // 更新测试申请单
    @PutMapping("/{id}")
    public Result<String> updateApplication(@PathVariable Long id, @RequestBody TestApplication application) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_UPDATE_ATTEMPT", "system", "尝试更新测试申请单");
        LogUtils.logApiRequest(logger, "PUT", "/api/applications/" + id, application != null ? application.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理更新测试申请单请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "更新测试申请单失败: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_UPDATE_FAILED", "system", "更新测试申请单失败: 申请单ID无效");
                return Result.fail("申请单ID无效");
            }
            
            // 验证请求对象
            if (application == null) {
                LogUtils.warn(logger, "更新测试申请单失败: 申请单信息对象为空");
                LogUtils.logBusiness(logger, "APPLICATION_UPDATE_FAILED", "system", "更新测试申请单失败: 申请单信息对象为空");
                return Result.fail("申请单信息无效");
            }
            
            LogUtils.debug(logger, () -> "获取更新测试申请单请求参数: 版本号=" + application.getVersion() + ", 产品ID=" + application.getProductId());
            
            // 设置申请单ID
            application.setId(id);
            LogUtils.debug(logger, () -> "设置申请单ID为路径参数中的ID值: " + id);
            
            LogUtils.info(logger, () -> "执行更新测试申请单操作，申请单ID=" + id);
            boolean success = testApplicationService.updateApplication(application);
            
            if (success) {
                LogUtils.debug(logger, () -> "更新测试申请单成功，申请单ID=" + id + ", 版本号=" + application.getVersion());
                LogUtils.logBusiness(logger, "APPLICATION_UPDATE_SUCCESS", "system", "更新测试申请单成功，申请单ID=" + id);
                LogUtils.logPerformance(logger, "updateApplication", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "更新测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("更新申请单成功");
            } else {
                LogUtils.warn(logger, "更新测试申请单失败: 已提交的申请单不允许修改，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_UPDATE_FAILED", "system", "更新测试申请单失败: 已提交的申请单不允许修改");
                return Result.fail("更新申请单失败，已提交的申请单不允许修改");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/applications/" + id, e);
            LogUtils.error(logger, "更新申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_UPDATE_FAILED", "system", "更新申请单失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "updateApplication", startTime, System.currentTimeMillis());
            return Result.fail("更新申请单失败: " + e.getMessage());
        }
    }
    
    // 删除测试申请单
    @DeleteMapping("/{id}")
    public Result<String> deleteApplication(@PathVariable Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_DELETE_ATTEMPT", "system", "尝试删除测试申请单");
        LogUtils.logApiRequest(logger, "DELETE", "/api/applications/" + id, null);
        LogUtils.debug(logger, () -> "开始处理删除测试申请单请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "删除测试申请单失败: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_DELETE_FAILED", "system", "删除测试申请单失败: 申请单ID无效");
                return Result.fail("申请单ID无效");
            }
            
            LogUtils.info(logger, () -> "执行删除测试申请单操作，申请单ID=" + id);
            boolean success = testApplicationService.deleteApplication(id);
            
            if (success) {
                LogUtils.debug(logger, () -> "删除测试申请单成功，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_DELETE_SUCCESS", "system", "删除测试申请单成功，申请单ID=" + id);
                LogUtils.logPerformance(logger, "deleteApplication", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "删除测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("删除申请单成功");
            } else {
                LogUtils.warn(logger, "删除测试申请单失败: 已提交的申请单不允许删除，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_DELETE_FAILED", "system", "删除测试申请单失败: 已提交的申请单不允许删除");
                return Result.fail("删除申请单失败，已提交的申请单不允许删除");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "DELETE", "/api/applications/" + id, e);
            LogUtils.error(logger, "删除申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_DELETE_FAILED", "system", "删除申请单失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "deleteApplication", startTime, System.currentTimeMillis());
            return Result.fail("删除申请单失败: " + e.getMessage());
        }
    }
    
    // 提交测试申请单
    @PutMapping("/{id}/submit")
    public Result<String> submitApplication(@PathVariable Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_SUBMIT_ATTEMPT", "system", "尝试提交测试申请单");
        LogUtils.logApiRequest(logger, "PUT", "/api/applications/" + id + "/submit", null);
        LogUtils.debug(logger, () -> "开始处理提交测试申请单请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "提交测试申请单失败: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_SUBMIT_FAILED", "system", "提交测试申请单失败: 申请单ID无效");
                return Result.fail("申请单ID无效");
            }
            
            LogUtils.info(logger, () -> "执行提交测试申请单操作，申请单ID=" + id);
            boolean success = testApplicationService.submitApplication(id);
            
            if (success) {
                LogUtils.debug(logger, () -> "提交测试申请单成功，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_SUBMIT_SUCCESS", "system", "提交测试申请单成功，申请单ID=" + id + "，等待平台审核");
                LogUtils.logPerformance(logger, "submitApplication", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "提交测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("提交申请单成功，等待平台审核");
            } else {
                LogUtils.warn(logger, "提交测试申请单失败: 仅待提交状态的申请单可以提交，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_SUBMIT_FAILED", "system", "提交测试申请单失败: 仅待提交状态的申请单可以提交");
                return Result.fail("提交申请单失败，仅待提交状态的申请单可以提交");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/applications/" + id + "/submit", e);
            LogUtils.error(logger, "提交申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_SUBMIT_FAILED", "system", "提交申请单失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "submitApplication", startTime, System.currentTimeMillis());
            return Result.fail("提交申请单失败: " + e.getMessage());
        }
    }
    
    // 平台审核-同意申请单
    @PutMapping("/{id}/approve")
    public Result<String> approveApplication(@PathVariable Long id, @RequestBody Map<String, String> params) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_APPROVE_ATTEMPT", "system", "尝试平台审核同意测试申请单");
        LogUtils.logApiRequest(logger, "PUT", "/api/applications/" + id + "/approve", params != null ? params.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理平台审核同意测试申请单请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "平台审核同意测试申请单失败: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_APPROVE_FAILED", "system", "平台审核同意测试申请单失败: 申请单ID无效");
                return Result.fail("申请单ID无效");
            }
            
            // 验证请求对象
            if (params == null) {
                LogUtils.warn(logger, "平台审核同意测试申请单失败: 请求参数为空");
                LogUtils.logBusiness(logger, "APPLICATION_APPROVE_FAILED", "system", "平台审核同意测试申请单失败: 请求参数为空");
                return Result.fail("请求参数无效");
            }
            
            String platformAuditOpinion = params.get("platformAuditOpinion");
            LogUtils.debug(logger, () -> "获取平台审核意见: " + platformAuditOpinion);
            
            LogUtils.info(logger, () -> "执行平台审核同意测试申请单操作，申请单ID=" + id);
            boolean success = testApplicationService.approveApplication(id, platformAuditOpinion);
            
            if (success) {
                LogUtils.debug(logger, () -> "平台审核同意测试申请单成功，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_APPROVE_SUCCESS", "system", "平台审核同意测试申请单成功，申请单ID=" + id + "，等待测试负责人审批");
                LogUtils.logPerformance(logger, "approveApplication", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "平台审核同意测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("审核通过，等待测试负责人审批");
            } else {
                LogUtils.warn(logger, "平台审核同意测试申请单失败: 仅待平台审核状态的申请单可以审核，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_APPROVE_FAILED", "system", "平台审核同意测试申请单失败: 仅待平台审核状态的申请单可以审核");
                return Result.fail("审核失败，仅待平台审核状态的申请单可以审核");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/applications/" + id + "/approve", e);
            LogUtils.error(logger, "审核申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_APPROVE_FAILED", "system", "审核失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "approveApplication", startTime, System.currentTimeMillis());
            return Result.fail("审核失败: " + e.getMessage());
        }
    }
    
    // 平台审核-拒绝申请单
    @PutMapping("/{id}/reject")
    public Result<String> rejectApplication(@PathVariable Long id, @RequestBody Map<String, String> params) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_REJECT_ATTEMPT", "system", "尝试平台审核拒绝测试申请单");
        LogUtils.logApiRequest(logger, "PUT", "/api/applications/" + id + "/reject", params != null ? params.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理平台审核拒绝测试申请单请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "平台审核拒绝测试申请单失败: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_REJECT_FAILED", "system", "平台审核拒绝测试申请单失败: 申请单ID无效");
                return Result.fail("申请单ID无效");
            }
            
            // 验证请求对象
            if (params == null) {
                LogUtils.warn(logger, "平台审核拒绝测试申请单失败: 请求参数为空");
                LogUtils.logBusiness(logger, "APPLICATION_REJECT_FAILED", "system", "平台审核拒绝测试申请单失败: 请求参数为空");
                return Result.fail("请求参数无效");
            }
            
            String platformAuditOpinion = params.get("platformAuditOpinion");
            LogUtils.debug(logger, () -> "获取平台审核意见: " + platformAuditOpinion);
            
            LogUtils.info(logger, () -> "执行平台审核拒绝测试申请单操作，申请单ID=" + id);
            boolean success = testApplicationService.rejectApplication(id, platformAuditOpinion);
            
            if (success) {
                LogUtils.debug(logger, () -> "平台审核拒绝测试申请单成功，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_REJECT_SUCCESS", "system", "平台审核拒绝测试申请单成功，申请单ID=" + id);
                LogUtils.logPerformance(logger, "rejectApplication", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "平台审核拒绝测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("已拒绝申请单");
            } else {
                LogUtils.warn(logger, "平台审核拒绝测试申请单失败: 仅待平台审核状态的申请单可以拒绝，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_REJECT_FAILED", "system", "平台审核拒绝测试申请单失败: 仅待平台审核状态的申请单可以拒绝");
                return Result.fail("拒绝失败，仅待平台审核状态的申请单可以拒绝");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/applications/" + id + "/reject", e);
            LogUtils.error(logger, "拒绝申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_REJECT_FAILED", "system", "拒绝失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "rejectApplication", startTime, System.currentTimeMillis());
            return Result.fail("拒绝失败: " + e.getMessage());
        }
    }
    
    // 测试负责人审批-同意
    @PutMapping("/{id}/manager-approve")
    public Result<String> testManagerApprove(@PathVariable Long id, @RequestBody Map<String, String> params) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_MANAGER_APPROVE_ATTEMPT", "system", "尝试测试负责人审批同意测试申请单");
        LogUtils.logApiRequest(logger, "PUT", "/api/applications/" + id + "/manager-approve", params != null ? params.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理测试负责人审批同意测试申请单请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "测试负责人审批同意测试申请单失败: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_MANAGER_APPROVE_FAILED", "system", "测试负责人审批同意测试申请单失败: 申请单ID无效");
                return Result.fail("申请单ID无效");
            }
            
            // 验证请求对象
            if (params == null) {
                LogUtils.warn(logger, "测试负责人审批同意测试申请单失败: 请求参数为空");
                LogUtils.logBusiness(logger, "APPLICATION_MANAGER_APPROVE_FAILED", "system", "测试负责人审批同意测试申请单失败: 请求参数为空");
                return Result.fail("请求参数无效");
            }
            
            String testManagerAuditOpinion = params.get("testManagerAuditOpinion");
            String testerIds = params.get("testerIds");
            LogUtils.debug(logger, () -> "获取测试负责人审批意见: " + testManagerAuditOpinion + ", 测试人员ID列表: " + testerIds);
            
            LogUtils.info(logger, () -> "执行测试负责人审批同意测试申请单操作，申请单ID=" + id);
            boolean success = testApplicationService.testManagerApprove(id, testManagerAuditOpinion, testerIds);
            
            if (success) {
                LogUtils.debug(logger, () -> "测试负责人审批同意测试申请单成功，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_MANAGER_APPROVE_SUCCESS", "system", "测试负责人审批同意测试申请单成功，申请单ID=" + id + "，等待测试");
                LogUtils.logPerformance(logger, "testManagerApprove", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "测试负责人审批同意测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("审批通过，等待测试");
            } else {
                LogUtils.warn(logger, "测试负责人审批同意测试申请单失败: 仅待测试负责人审批状态的申请单可以审批，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_MANAGER_APPROVE_FAILED", "system", "测试负责人审批同意测试申请单失败: 仅待测试负责人审批状态的申请单可以审批");
                return Result.fail("审批失败，仅待测试负责人审批状态的申请单可以审批");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/applications/" + id + "/manager-approve", e);
            LogUtils.error(logger, "审批申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_MANAGER_APPROVE_FAILED", "system", "审批失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "testManagerApprove", startTime, System.currentTimeMillis());
            return Result.fail("审批失败: " + e.getMessage());
        }
    }
    
    // 测试负责人审批-拒绝
    @PutMapping("/{id}/manager-reject")
    public Result<String> testManagerReject(@PathVariable Long id, @RequestBody Map<String, String> params) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_MANAGER_REJECT_ATTEMPT", "system", "尝试测试负责人审批拒绝测试申请单");
        LogUtils.logApiRequest(logger, "PUT", "/api/applications/" + id + "/manager-reject", params != null ? params.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理测试负责人审批拒绝测试申请单请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "测试负责人审批拒绝测试申请单失败: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_MANAGER_REJECT_FAILED", "system", "测试负责人审批拒绝测试申请单失败: 申请单ID无效");
                return Result.fail("申请单ID无效");
            }
            
            // 验证请求对象
            if (params == null) {
                LogUtils.warn(logger, "测试负责人审批拒绝测试申请单失败: 请求参数为空");
                LogUtils.logBusiness(logger, "APPLICATION_MANAGER_REJECT_FAILED", "system", "测试负责人审批拒绝测试申请单失败: 请求参数为空");
                return Result.fail("请求参数无效");
            }
            
            String testManagerAuditOpinion = params.get("testManagerAuditOpinion");
            LogUtils.debug(logger, () -> "获取测试负责人审批意见: " + testManagerAuditOpinion);
            
            LogUtils.info(logger, () -> "执行测试负责人审批拒绝测试申请单操作，申请单ID=" + id);
            boolean success = testApplicationService.testManagerReject(id, testManagerAuditOpinion);
            
            if (success) {
                LogUtils.debug(logger, () -> "测试负责人审批拒绝测试申请单成功，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_MANAGER_REJECT_SUCCESS", "system", "测试负责人审批拒绝测试申请单成功，申请单ID=" + id);
                LogUtils.logPerformance(logger, "testManagerReject", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "测试负责人审批拒绝测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("已拒绝申请单");
            } else {
                LogUtils.warn(logger, "测试负责人审批拒绝测试申请单失败: 仅待测试负责人审批状态的申请单可以拒绝，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_MANAGER_REJECT_FAILED", "system", "测试负责人审批拒绝测试申请单失败: 仅待测试负责人审批状态的申请单可以拒绝");
                return Result.fail("拒绝失败，仅待测试负责人审批状态的申请单可以拒绝");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/applications/" + id + "/manager-reject", e);
            LogUtils.error(logger, "拒绝申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_MANAGER_REJECT_FAILED", "system", "拒绝失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "testManagerReject", startTime, System.currentTimeMillis());
            return Result.fail("拒绝失败: " + e.getMessage());
        }
    }
    
    // 取消测试申请单
    @PutMapping("/{id}/cancel")
    public Result<String> cancelApplication(@PathVariable Long id, @RequestBody Map<String, String> params) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "APPLICATION_CANCEL_ATTEMPT", "system", "尝试取消测试申请单");
        LogUtils.logApiRequest(logger, "PUT", "/api/applications/" + id + "/cancel", params != null ? params.toString() : "空请求");
        LogUtils.debug(logger, () -> "开始处理取消测试申请单请求，申请单ID=" + id);
        
        try {
            // 验证参数
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "取消测试申请单失败: 申请单ID必须大于0，当前值=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_CANCEL_FAILED", "system", "取消测试申请单失败: 申请单ID无效");
                return Result.fail("申请单ID无效");
            }
            
            // 验证请求对象
            if (params == null) {
                LogUtils.warn(logger, "取消测试申请单失败: 请求参数为空");
                LogUtils.logBusiness(logger, "APPLICATION_CANCEL_FAILED", "system", "取消测试申请单失败: 请求参数为空");
                return Result.fail("请求参数无效");
            }
            
            String reason = params.get("reason");
            LogUtils.debug(logger, () -> "获取取消申请单原因: " + reason);
            
            LogUtils.info(logger, () -> "执行取消测试申请单操作，申请单ID=" + id);
            boolean success = testApplicationService.cancelApplication(id, reason);
            
            if (success) {
                LogUtils.debug(logger, () -> "取消测试申请单成功，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_CANCEL_SUCCESS", "system", "取消测试申请单成功，申请单ID=" + id);
                LogUtils.logPerformance(logger, "cancelApplication", startTime, System.currentTimeMillis());
                
                LogUtils.info(logger, () -> "取消测试申请单请求处理完成，耗时=" + (System.currentTimeMillis() - startTime) + "ms");
                return Result.success("已取消申请单");
            } else {
                LogUtils.warn(logger, "取消测试申请单失败: 测试中或已驳回的申请单不允许取消，申请单ID=" + id);
                LogUtils.logBusiness(logger, "APPLICATION_CANCEL_FAILED", "system", "取消测试申请单失败: 测试中或已驳回的申请单不允许取消");
                return Result.fail("取消失败，测试中或已驳回的申请单不允许取消");
            }
        } catch (Exception e) {
            LogUtils.logApiError(logger, "PUT", "/api/applications/" + id + "/cancel", e);
            LogUtils.error(logger, "取消申请单过程发生异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "APPLICATION_CANCEL_FAILED", "system", "取消失败: " + e.getMessage());
            LogUtils.logPerformance(logger, "cancelApplication", startTime, System.currentTimeMillis());
            return Result.fail("取消失败: " + e.getMessage());
        }
    }
    
    // 获取申请单历史记录
    @GetMapping("/{id}/history")
    public Result<List<?>> getApplicationHistory(@PathVariable Long id) {
        try {
            return Result.success(testApplicationService.getApplicationHistory(id));
        } catch (Exception e) {
            return Result.fail("获取历史记录失败: " + e.getMessage());
        }
    }
}